<template>
  <view class="all-content">
    <!-- 视频-->
    <view class="video-content">
      <!-- 视频播放框 -->
      <video
          id="myVideo"
          class="video-box"
          :src="videoPlayUrl"
          :poster="videoPosterUrl"
          :title="videoName"
          @play="videoPlayAction"
          @pause="videoPauseAction"
          @ended="videoEndedAction"
          @waiting="videoWaitingAction"
          @error="videoErrorAction"
          @timeupdate="videoTimeUpdateAction"
          @loadedmetadata="videoLoadeMetaDataAction"
      ></video>
    </view>
    <view class="video-name">
      <text class="video-name-text">{{ videoName }}</text>
    </view>
    <view v-if="videoDescription.length > 0" class="video-description">
      <view class="video-line"></view>
      <text class="video-description-text">简介：{{ videoDescription }}</text>
    </view>
    <view v-if="isStudy" class="time-box" :style="{backgroundImage: `url(${timeBgImg})`}">
      <view v-if="isStudyFinish" class="time-detail-box">
        <text class="time-text time-finish-text">已完成学习</text>
      </view>
      <view v-else class="time-detail-box">
        <text class="time-text">观看</text>
        <text class="time-text time-num-text">{{readMinute}}</text>
        <text class="time-text">:</text>
        <text class="time-text time-num-text">{{readSecond}}</text>
        <text class="time-text">分钟</text>
      </view>
    </view>
  </view>
</template>

<script>
import {isEmpty, prefixInteger, showToast} from "@/utils/utils";
import Api, {imgHost} from "@/utils/api";
import {getItem} from "@/utils/storage";
import {GLOBAL_USER_ID} from "@/utils/const";
import {postRequest} from "@/utils/request";

export default {
  name: "index",
  components: {},
  data() {
    return {
      videoType: 1, // 导航栏状态 1：非助农视频（红色） 2：助农视频（绿色）
      videoContext: null, // 视频容器对象
      videoId: "", // 视频ID
      videoName: "视频播放", // 视频名称
      videoPosterUrl: imgHost + 'video_poster.jpg', // 视频封面地址
      videoPlayUrl: "", // 视频播放地址
      videoDescription: "", // 视频简介
      isStudy: false, // 是否是党员学习
      isStudyFinish: false, // 是否已阅读学习
      timeBgImg: imgHost + 'icon_time_bg.png',  // 计时器背景图
      readTimer: null,
      readMinute: '00',
      readSecond: '00',
      videoFullTime: 0, // 视频总时长
    }
  },
  onLoad(option) {
    console.log(option)
    this.videoId = !isEmpty(option.videoId) ? option.videoId : this.videoId;
    this.videoName = !isEmpty(option.videoName) ? option.videoName : this.videoName;
    this.videoPosterUrl = !isEmpty(option.videoPosterUrl) ? option.videoPosterUrl : this.videoPosterUrl;
    this.videoType = !isEmpty(option.videoType) ? parseInt(option.videoType) : 1
    this.videoDescription = !isEmpty(option.videoDescription) ? option.videoDescription : ""
    this.isStudy = option.isStudy

    uni.setNavigationBarTitle({
      title: this.videoName
    })
    // uni.setNavigationBarColor({
    //   frontColor: '#ffffff',
    //   backgroundColor: this.videoType === 1 ? '#22B790' : '#2F7F00'
    // })

    if (!isEmpty(option.videoPlayUrl)) {
      this.videoPlayUrl = option.videoPlayUrl;
    } else {
      uni.showModal({
        content: "当前视频资源未获取到，请退出重试!",
        showCancel: false,
        success: function (res) {
          uni.navigateBack({
            delta: 1
          })
        },
        fail: function (res) {
          uni.navigateBack({
            delta: 1
          })
        }
      })
      return;
    }
    if (this.videoPlayUrl) {
      this.getVideoDetail();
    }
  },
  methods: {
    // 学习倒计时
    readCountTime(times) {
      const nowTime = new Date().getTime()
      const leftTime = new Date(times - nowTime)
      if (leftTime >= 0) {
        // const readHour = leftTime.getHours()
        this.readMinute = prefixInteger(leftTime.getMinutes(), 2)
        this.readSecond = prefixInteger(leftTime.getSeconds(), 2)

        this.readTimer = setTimeout(() => {
          this.readCountTime(times)
        }, 1000)
      } else {
        this.readTimer && clearTimeout(this.readTimer)
        this.readTimer = null
        this.isStudyFinish = true
        this.studyFinishAddTime()
      }
    },
    // 学习完成增加时长
    studyFinishAddTime() {
      const params = {
        userId: getItem(GLOBAL_USER_ID),
        contentType: 1,
        contentId: this.videoId,
        studyTime: this.videoFullTime
      }
      postRequest(Api.StudyLearn, params)
          .then(res => {
            showToast('已完成学习')
            const pages = getCurrentPages();
            const prePage = pages[pages.length - 2]; // 上一个页面
            prePage.$vm.refreshPageData()
          })
    },
    // 当开始/继续播放时触发play事件
    videoPlayAction(e) {
      console.log("play: ", e.detail)
    },
    // 当暂停播放时触发 pause 事件
    videoPauseAction(e) {
      console.log("pause: ", e.detail)
    },
    // 当播放到末尾时触发 ended 事件
    videoEndedAction(e) {
      console.log("ended: ", e.detail)
    },
    // 视频出现缓冲时触发
    videoWaitingAction(e) {
      console.log("waiting: ", e.detail)
    },
    // 视频播放出错
    videoErrorAction(e) {
      uni.showModal({
        content: "该视频资源无法播放，请至web端查看。",
        showCancel: false,
        success: function (res) {
          uni.navigateBack({
            delta: 1
          })
        },
        fail: function (res) {
          uni.navigateBack({
            delta: 1
          })
        }
      })
    },
    // 播放进度变化时触发，event.detail = {currentTime, duration} 。触发频率 250ms 一次
    videoTimeUpdateAction(e) {
      // console.log("timeUpdate: ", e.detail)
    },
    // 视频元数据加载完成时触发。event.detail = {width, height, duration}
    videoLoadeMetaDataAction(e) {
      console.log("loadeMetaData: ", e.detail)
      this.videoFullTime = e.detail.duration
      this.readCountTime(new Date().getTime() + e.detail.duration * 1000)
    },
    // 初始化视频播放器
    getVideoDetail(videoId) {
      const self = this;
      this.videoContext = uni.createVideoContext('myVideo');
      setTimeout(() => {
        self.videoContext.play();
      }, 500)
    }
  },
  onUnload() {
    this.readTimer && clearTimeout(this.readTimer)
    this.readTimer = null
    console.log('页面卸载')
  }
}
</script>

<style lang="scss" scoped>
.all-content {
  .video-content {
    width: 100vw;
    height: 56.25vw;
    .video-box {
      width: 100%;
      height: 100%;
    }
  }
  .video-name {
    display: flex;
    flex-direction: row;
    margin: 30rpx 20rpx;
    .video-name-text {
      width: 100%;
      color: #333333;
      font-size: 38rpx;
      font-weight: bold;
      line-height: 48rpx;
      word-wrap: break-word;
    }
  }
  .video-description {
    display: flex;
    flex-direction: column;
    margin: 0 20rpx 30rpx 20rpx;
    .video-line {
      height: 1rpx;
      margin-bottom: 30rpx;
      background-color: #E5E5E5;
    }
    .video-description-text {
      width: 100%;
      font-size: 26rpx;
      color: #666666;
      line-height: 35rpx;
      word-wrap: break-word;
    }
  }
  .time-box {
    position: fixed;
    background-size: 100% 100%;
    right: 10rpx;
    bottom: 180rpx;
    width: 265rpx;
    height: 210rpx;
    display: flex;
    align-items: flex-end;
    .time-detail-box {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      height: 90rpx;
      width: 100%;
      .time-text {
        color: #FFFFFF;
        font-weight: bolder;
        font-size: $center-size-x;
        margin: 0 5rpx;
      }
      .time-finish-text {
        font-size: $center-size-xxx;
      }
      .time-num-text {
        background: linear-gradient(0deg, rgba(241,42,39,0.99), rgba(196,17,14,0.99), rgba(241,42,39,0.99));
        border-radius: 10rpx;
        font-size: $center-size-xxx;
        padding: 5rpx;
        min-width: 40rpx;
        text-align: center;
      }
    }
  }
}
</style>
